const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const authService = require('./auth');
const { messagesDB } = require('./database');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: '*' }
});

// WebSocket连接处理
io.use(async (socket, next) => {
  try {
    const token = socket.handshake.auth.token;
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    socket.userId = decoded.userId;
    next();
  } catch (error) {
    next(new Error('认证失败'));
  }
});

io.on('connection', (socket) => {
  console.log(`用户 ${socket.userId} 已连接`);

  socket.on('sendMessage', async ({ content, receiver }) => {
    const message = {
      sender: socket.userId,
      receiver,
      content,
      timestamp: new Date().toISOString()
    };
    
    await messagesDB.insert(message);
    io.to(receiver).emit('newMessage', message);
  });

  socket.on('disconnect', () => {
    console.log(`用户 ${socket.userId} 已断开连接`);
  });
});

server.listen(3001, () => {
  console.log('服务器运行在 http://localhost:3001');
});
